#!/usr/bin/env coffee

import '@rmw/console/global'
import dgram from 'dgram'
import CONFIG from '@rmw/config'
import txtli from './txtli'
import split_n from 'split_n'
import onMessage from './msg/_on'
import init from './init'
import {hi} from './msg/_call'

do =>
  awaitInit = init()
  {PORT} = CONFIG

  socket = dgram.createSocket('udp4')

  socket.on 'error', (err) =>
    {code} = err
    if code == "EADDRINUSE"
      socket.bind()
      return
    console.log "❌", socket.address(), err.code, err.message
    return

  socket.on 'message', onMessage.bind(socket)

  socket.on 'listening',=>
    host = socket.address()
    {address, port} = host
    if not PORT
      CONFIG.PORT = port
    console.log "绑定端口", "#{address}:#{port}"

    await awaitInit

    for i in txtli("./ip.txt")
      [ip,port] = split_n(i, ":", 2)
      port = parseInt port
      socket.send(
        hi(ip, port)
        port
        ip
      )
      console.log "尝试连接",ip,port

  socket.on 'close', =>
    console.log "socket close"
    process.exit()

  socket.bind(PORT)

